import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import AddOrEditUser from './addOrEditUser';
import Detail from './../IssueTicket/Detail';

const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ message, loading, global }) => ({
  message,
  global,
  loading: loading.models.message,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      message: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        message: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'message/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'message/changeLoaded',
          });
          dispatch({
            type: 'message/changeTableY',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'message/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'message/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.react-grid-Canvas');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'message/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      message: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem>

          <FormItem label="用户手机号">
            {getFieldDecorator('title', {
              initialValue: searchParams.title,
            })(<Input style={{ width: '150px' }} placeholder="请输入"/>)}
          </FormItem>
          <FormItem label="状态">
            {getFieldDecorator('status', {
              initialValue: searchParams.status,
            })(
              <Select style={{width:'100px'}}>
                {
                  [{id:'',value:'全部'} ,{id:'1',value:'已回复'},{id:'-1',value:'未回复'}].map((item,index)=>{
                    return <Option key={index} value={item.id}>{item.value}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }

  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'message/add',
      payload: {
        ...formValues,
      },
      callback() {
        message.success('发布新巡检工单成功');
        that.setState({
          addModal: false,
        });
        const {
          message: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      title:'',
      device_number:'',
      status:'',
      page: 1,
      per_page: 30,
    });
  };

  handleComplete = () => {
    console.log('this.CompleteForm.props.form.',this.CompleteForm.state.fileList.length)
    this.setState({ loading: true });
    const formValues = this.CompleteForm.props.form.getFieldsValue();
    const that = this;
    this.props.dispatch({
      type: `message/edit`,
      payload: {
        id: this.state.editRecord.id,
        reply: formValues.reply,

      },
      callback() {
        message.success('完成巡检工单成功');
        that.setState({
          completeModal: false,
          loading: false
        });
        const {
          message: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
    setTimeout(function() {
      that.setState({
        loading: false
      });
    },5000)
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `message/remove`,
      payload: { id },
      callback: () => {
        message.success('删除留言成功');
        const {
          message: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleClick = (key,mobile) => {
    console.log('key)', key);
    const { panes, routerMapping } = this.props.global;
    const {dispatch} =this.props;
    const activeKey = key;
    const that=this;
    if (find(panes, o => o.key == activeKey)) {
      console.log('已经存在');
    } else {
      panes.push({
        title: find(routerMapping, o => o.path == activeKey).name,
        content: 'New Tab Pane',
        key: activeKey,
      });
    }
    dispatch(routerRedux.push(activeKey));
    dispatch({
      type: 'global/changePanesAndActive',
      payload: { panes, activeKey },
      callback:function() {
        const {
          message: { searchParams},
          global:{gridTableW}
        } = that.props;
        const sendSearchParams= {
          region_id:'',
          region_name:'',
          status:'0',
          balance_status:'0',
          caliber:'',
          name:'',
          mobile:mobile,
          meter_number:'',
          address:'',
          filter_level:'',
          filter_year:'',
          page: 1,
          per_page: 50,
        };
        console.log('sendSearchParams', sendSearchParams);
        dispatch({
          type: 'owner/changeLoadedFalse',
          callback:function() {
            dispatch({
              type: 'owner/changeSearchParams',
              payload: sendSearchParams,
            });
          }
        });

        dispatch({
          type: 'owner/changeOneProperty',
          payload: {
            searchInputText:mobile
          },
        });

      }
    });
  };

  render() {
    const that = this;
    const {
      message: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            message: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '创建时间',
        key: 'created_at',
        width: 150,
        frozen: true,

      },
      {
        name: '用户手机',
        key: 'mobile',
        width: 120,
        frozen: true,
        formatter:(event)=>{
          return <span title={event.value} style={{color:'blue',cursor:'pointer'}} onClick={()=>{
            this.handleClick('/owner',event.value)
          }}>{event.value}</span>
        }
      },
      {
        name: '主题',
        width: 180,
        key: 'title',
        frozen: true,
      },
      {
        name: '内容',
        width: 180,
        key: 'content',
      },
      {
        name: '状态',
        key: 'status',
        width: 100,
        formatter: (event) => {
          switch (event.value) {
            case -1:
              return <p className={ 'table-error table-status' }>未回复</p>;
            case 1:
              return <p className={ 'table-success table-status' }>已回复</p>;
          }

        },
      },
      {
        name: '回复人',
        width: 160,
        key: 'replier',
        formatter: (event) => {
          return (event.row.replier.name?`${event.row.replier.department_name} / ${event.row.replier.name}`:'') ;
        },
      },
      {
        name: '回复内容',
        width: 150,
        key: 'reply',
      },
      {
        name: '操作',
        width: 240,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          {
            <Fragment>
              <Button
                className={'btn-green'}
                type="primary"
                size="small"
                icon="form"
                onClick={(e) => {
                  that.setState({
                    editRecord: event.row,
                    completeModal: true,
                  });
                }
                }
              >回复
              </Button>
              <Button
                type="danger"
                size="small"
                icon="delete"
                onClick={(e) => {
                  confirm({
                    title: `确定要删除"${event.row.title}"吗?`,
                    content: '请谨慎操作！',
                    okText: '确定',
                    okType: 'danger',
                    cancelText: '取消',
                    centered: true,
                    maskClosable: true,
                    onOk() {
                      that.handleDelete(event.row.id);
                    },
                    onCancel() {
                      console.log('Cancel');
                    },
                  });
                }
                }
              >删除
              </Button>
            </Fragment>
          }

        </Fragment>,
      },

    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>公众号留言</span>
      </div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                this.props.dispatch({
                  type: 'message/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.completeModal} modalClass="completeModal"
                                title={`留言" ${this.state.editRecord.title} "回复`}/>}
        destroyOnClose
        visible={this.state.completeModal}
        centered
        onOk={this.handleComplete}
        className="completeModal"
        width={600}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ completeModal: false, editRecord: {} });
        }}
        confirmLoading={this.state.loading}
      >
        <AddOrEditUser
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.CompleteForm = inst}/>
      </Modal>
      <Drawer
        title={`工单详情详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}

        width={700}
        visible={this.state.infoModal}
      >
        <Detail id={this.state.editRecord.id}></Detail>
      </Drawer>
    </div>;
  }
}

export default BasicList;
